//
//  SGUtil.m
//  sguo
//
//

#import "SGUtil.h"
#import <CommonCrypto/CommonDigest.h>
#import "QYGNetRequestModel.h"
#import "QYGPaymentModel.h"

@interface SGUtil()

@property (nonatomic, assign) NSInteger requestCount;
@property (strong, nonatomic) NSTimer *requestTimer;

@end


@implementation SGUtil

/**
 验证微信登录

 */
+ (BOOL)WXAppIsInstalled{
    
    if (![WXApi isWXAppInstalled]) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请先安装微信客户端" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        return NO;
    }
    return YES;
}

/**
 微信回调
 
 */
- (void)onResp:(BaseResp *)resp {
    // 向微信请求授权后,得到响应结果
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp *temp = (SendAuthResp *)resp;
        NSString *code = temp.code;
        if(self.wxLoginCompleteBlock){
            self.wxLoginCompleteBlock(code);
        }
    }
    //启动微信支付的response
//    NSString *payResoult = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
    if([resp isKindOfClass:[PayResp class]]){
        
//        if(self.wxPayCompleteBlock){
//            self.wxPayCompleteBlock(resp.errCode);
//        }
        //支付返回结果，实际支付结果需要去微信服务器端查询
        switch (resp.errCode) {
            case 0:
                // @"支付结果：成功！";
                // 交易单号查询
                 [SVProgressHUD showWithStatus:@"支付中..."];
                KeyWindow.userInteractionEnabled = NO;
                self.requestTimer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(requestAction) userInfo:nil repeats:YES];
                
                break;
            case -1:
                // @"支付结果：失败！";
                [self showPayResult:NO];
                
                break;
            case -2:
                // @"用户已经退出支付！";
                [self showPayResult:NO];
                break;
            default:
                
                [self showPayResult:NO];
                
                break;
        }
    }
}


- (void)requestAction{
    
    self.requestCount += 1;
    [QYGNetRequestModel getCheckPaymentWithPay_id:self.pay_id completed:^(QYGPaymentModel *paymentModel) {
        
        if( [paymentModel.status isEqualToString:@"paid"]){
            [SVProgressHUD dismiss];
            KeyWindow.userInteractionEnabled = YES;
            [self showPayResult:YES];
            
        }else{
            if(self.requestCount >5){
                [SVProgressHUD dismiss];
                // 支付失败
                KeyWindow.userInteractionEnabled = YES;
                [self showPayResult:NO];
            }
        }
    } WithErrorCodeBlock:^(NSError *error) {
        
        if(self.requestCount >5){
            [SVProgressHUD dismiss];
            KeyWindow.userInteractionEnabled = YES;
            // 支付失败
            [self showPayResult:NO];
        }
    }];
}

- (void)showPayResult:(BOOL)isSuccess{
//
    [self.requestTimer invalidate];
    self.requestTimer = nil;
    self.requestCount = 0;
    
    if(self.rechargeBlock){
        self.rechargeBlock(isSuccess, self.coinListModel);
        
    }
}

#pragma mark 微信支付方法
+ (void)WXPayWithOpenId:(NSString *)openID partnerId:(NSString *)partnerId prepayId:(NSString *)prepayId package:(NSString *)package nonceStr:(NSString *)nonceStr stamp:(NSString *)stamp sign:(NSString *)sign{
    
    //需要创建这个支付对象
    PayReq *req   = [[PayReq alloc] init];
    //由用户微信号和AppID组成的唯一标识，用于校验微信用户
    req.openID = openID;
    
    // 商家id，在注册的时候给的
    req.partnerId = partnerId;
    
    // 预支付订单这个是后台跟微信服务器交互后，微信服务器传给你们服务器的，你们服务器再传给你
    req.prepayId  = prepayId;
    // 根据财付通文档填写的数据和签名
    //这个比较特殊，是固定的，只能是即req.package = Sign=WXPay
    req.package   = package;
    
    // 随机编码，为了防止重复的，在后台生成
    req.nonceStr  = nonceStr;
    
    // 这个是时间戳，也是在后台生成的，为了验证支付的
//    NSString * stamp = @"";
    req.timeStamp = stamp.intValue;
    
    // 这个签名也是后台做的
    req.sign = sign;
    
    //发送请求到微信，等待微信返回onResp
    [WXApi sendReq:req];
}


+ (NSString *) compareCurrentTime:(NSString *)str
{
    //把字符串转为NSdate
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *timeDate = [dateFormatter dateFromString:str];
    NSDate *currentDate = [NSDate date];
    
    //得到两个时间差
    long timeInterval = (long)[currentDate timeIntervalSinceDate:timeDate];
//    long temp = 0;
    NSString *result;
    if (timeInterval < 60)
    {
        result = [NSString stringWithFormat:@"%ld秒前",timeInterval];
    }
    else if((timeInterval/60) <60){
        result = [NSString stringWithFormat:@"%ld分钟%ld秒前",timeInterval/60,timeInterval%60];
    }
    else {
        result = [NSString stringWithFormat:@"%ld小时%ld分钟%ld秒前",timeInterval/60/60,timeInterval/60/60/60,timeInterval/60/60%60];
    }
    return  result;
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        return nil;
    }
    return dic;
}
+ (NSData *)dictionaryToJsonData:(NSDictionary *)dic
{
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return jsonData;
    
}
+ (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

+ (UILabel *)newLabelWithFont:(UIFont *)font textColor:(UIColor *)textColor text:(NSString *)text {
    UILabel *label = [[UILabel alloc] init];
    label.font = font;
    label.text = text;
    label.textColor = textColor;
    
    return label;
}

+ (UIButton *)newButtonWithTitleFont:(UIFont *)font title:(NSString *)title titleColor:(UIColor *)titleColor {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.titleLabel.font = font;
    [button setTitleColor:titleColor forState:UIControlStateNormal];
    [button setTitle:title forState:UIControlStateNormal];
    return button;
}

+ (UIView *)newViewWithBgColor:(UIColor *)bgColor {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = bgColor;
    
    return view;
}
static SGUtil *_instance;
+(instancetype)allocWithZone:(struct _NSZone *)zone
{
    //    @synchronized (self) {
    //        // 为了防止多线程同时访问对象，造成多次分配内存空间，所以要加上线程锁
    //        if (_instance == nil) {
    //            _instance = [super allocWithZone:zone];
    //        }
    //        return _instance;
    //    }
    // 也可以使用一次性代码
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_instance == nil) {
            _instance = [super allocWithZone:zone];
        }
    });
    return _instance;
}
+(instancetype)shareUtil
{
    //return _instance;
    // 最好用self 用Tools他的子类调用时会出现错误
    return [[self alloc]init];
}
-(id)copyWithZone:(NSZone *)zone
{
    return _instance;
}
-(id)mutableCopyWithZone:(NSZone *)zone
{
    return _instance;
}

@end
